package com.hfzy.ihk.web.aliyuncall.biz;


import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dyvmsapi.model.v20170525.ClickToDialRequest;
import com.aliyuncs.dyvmsapi.model.v20170525.ClickToDialResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.hfzy.ihk.facade.aliyuncall.vo.CallHistory;
import com.hfzy.ihk.web.aliyuncall.constant.AliyunAkInfo;
import com.hfzy.ihk.web.aliyuncall.constant.Constants;
import com.hfzy.ihk.web.aliyuncall.context.DisruptorInitBean;
import com.hfzy.ihk.web.aliyuncall.support.disruptor.DisruptorSupport;
import com.hfzy.ihk.web.aliyuncall.support.disruptor.base.DisruptorEvent;
import com.hfzy.ihk.web.aliyuncall.vo.AliyunCallState;
import com.hfzy.ihk.web.aliyuncall.vo.CallOutParam;
import com.hfzy.ihk.web.aliyuncall.vo.CallOutVo;
import com.lmax.disruptor.RingBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 阿里云外呼业务处理类
 */
@Lazy
@Component("aliyunCallOutBiz")
public class AliyunCallOutBiz extends DisruptorSupport<CallHistory,DisruptorEvent<CallHistory>> {

    Logger logger = LoggerFactory.getLogger(AliyunCallOutBiz.class);

    @Resource
    private DisruptorInitBean disruptorInitBean;

    @Override
    protected RingBuffer<DisruptorEvent<CallHistory>> useRingBuffer(CallHistory data) {
        RingBuffer ringBuffer = null;
        String useType = "阿里云呼出";
        ringBuffer = disruptorInitBean.getRingBufferAliyunCallOut();
        checkRingBufferUse(ringBuffer,useType);
        return ringBuffer;
    }


    /**
     * 进队列呼出
     *
     * @param data
     * @throws Exception
     */
    public void todoCallOut(CallHistory data) throws Exception{
        putInRingBuffer(data);
    }




    /**
     *aliyun 外呼api调用
     * @param callOutVo
     * @return
     */
    public Map<String,String> callOutOpt(CallOutParam callOutVo){


        //云通信产品-语音API服务产品名称（产品名固定，无需修改）
        final String product = "Dyvmsapi";
        //语音API服务产品域名（接口地址固定，无需修改）
        final String domain = "dyvmsapi.aliyuncs.com";

        Map<String,String> map = new HashMap<>();

        try {
            //设置访问超时时间
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            //初始化acsClient暂时不支持多region（暂时固定，无需修改）
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", AliyunAkInfo.accessKeyId, AliyunAkInfo.accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);

            //组装请求对象-具体描述见控制台-文档部分内容
            ClickToDialRequest request = new ClickToDialRequest();
            //必填-主叫显号,可在语音控制台中找到所购买的显号
            request.setCallerShowNumber(callOutVo.getMainCallPhoneShow());
            //必填-主叫号码
            request.setCallerNumber(callOutVo.getMainCallPhone());
            //必填-被叫显号,可在语音控制台中找到所购买的显号
            request.setCalledShowNumber(callOutVo.getTargetCallPhoneShow());
            //必填-被叫号码
            request.setCalledNumber(callOutVo.getTargetCallPhone());
            //可选-外部扩展字段
            request.setOutId(callOutVo.getExtend());
            request.setAsrFlag(true); //是否开启 实时语音识别 默认否
            request.setRecordFlag(true);//是否录音
            //hint 此处可能会抛出异常，注意catch
            ClickToDialResponse clickToDialResponse = acsClient.getAcsResponse(request);
            logger.info("aliyun call out result param->RequestId:{},Code:{},Message:{},CallId:{}",
                    clickToDialResponse.getRequestId(),clickToDialResponse.getCode(),clickToDialResponse.getMessage(),clickToDialResponse.getCallId());

            if (clickToDialResponse.getCode() != null && clickToDialResponse.getCode().equals("OK")) {
                map.put("result", Constants.SUCCESS);
                map.put("msg",clickToDialResponse.getMessage());
                map.put("callOutCode",clickToDialResponse.getCode());
                map.put("callId",clickToDialResponse.getCallId());
                map.put("requestId",clickToDialResponse.getRequestId());
                //请求成功
            }else{
                map.put("result", Constants.FAIL);
                map.put("callOutCode",clickToDialResponse.getCode());
                map.put("msg",clickToDialResponse.getMessage());
                map.put("callId",clickToDialResponse.getCallId());
                map.put("requestId",clickToDialResponse.getRequestId());
            }
        }catch (Exception e){
            e.printStackTrace();
            map.put("result", Constants.FAIL);
            map.put("msg","外呼失败，请重试");
        }
        return map;

    }


}
